package com.mp.ipm2020.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mp.ipm2020.admin.AdminApplication;
import com.mp.ipm2020.admin.sevice.MqttSendSevice;
import com.mp.ipm2020.common.api.CommonPage;
import com.mp.ipm2020.common.api.CommonResult;
import com.mp.ipm2020.mbg.dto.ControlData;
import com.mp.ipm2020.mbg.model.Control;
import com.mp.ipm2020.mbg.service.ControlService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @Auther adidasshe@mp.cn
 * 设备控制 Controller
 */
@Api(tags = "设备控制")
@RestController
@RequestMapping("/control")
public class ControlController {
    protected static final Logger logger = LoggerFactory.getLogger(AdminApplication.class);

    @Autowired
    private ControlService controlService;
    @Autowired
    private MqttSendSevice mqttSendSevice;

    private long sendTime = 30;
    private long time = 30;

    @ApiOperation("分页查询设备控制表")
    @GetMapping()
    public CommonResult<CommonPage<Control>> list(@RequestParam(value = "keyword", required = false) String keyword,
                                                  @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                  @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        List<Control> list = controlService.list(keyword, pageSize, pageNum);
        return CommonResult.success(CommonPage.restPage(list));
    }

    @ApiOperation("添加设备控制记录")
    @PostMapping
    public CommonResult create(@RequestBody ControlData controlData) {
        Control control = new Control();
        QueryWrapper<Control> wrapper = new QueryWrapper<>();
        List<Control> list = null;
        //判断上次该设备下发控制指令时间
        //如果是下发开关1
        if (controlData.getSwitchSet1() == 1) {
            wrapper.eq("device_id", controlData.getDeviceId())
                    .eq("switch_set1", 1)
                    .orderByDesc("id")
                    .last("limit 1");
            list = controlService.list(wrapper);
        } else if (controlData.getSwitchSet2() == 1) {
            //如果是下发开关2
            wrapper.eq("device_id", controlData.getDeviceId())
                    .eq("switch_set2", 1)
                    .orderByDesc("id")
                    .last("limit 1");
            list = controlService.list(wrapper);
        } else if (controlData.getSwitchSet3() == 1) {
            //如果是下发开关3
            wrapper.eq("device_id", controlData.getDeviceId())
                    .eq("switch_set3", 1)
                    .orderByDesc("id")
                    .last("limit 1");
            list = controlService.list(wrapper);
        }

        //通过以上判断如果没有开关下发，或没有开关下发记录则直接可以下发控制
        if (list == null) {
            System.out.println("直接下发阈值");

        } else if (list.size() != 0) {
            //如果有下发记录则计算上条下发时间是不是操过30秒
            Control lastControl = list.get(0);
            time = (System.currentTimeMillis() - lastControl.getCreateTime().getTime()) / 1000;
        }

        if (time < sendTime) {
            System.out.println("时间差：" + time);
            return CommonResult.failed("请间隔： " + (sendTime - time) + "秒后再下发控制命令");

        } else {
            control.setCreateTime(new Date());
            control.setCtVarValue(controlData.getCtVarValue());
            control.setLeakageCurrentSet1(controlData.getLeakageCurrentSet1());
            control.setLeakageCurrentSet2(controlData.getLeakageCurrentSet2());
            control.setLeakageCurrentSet3(controlData.getLeakageCurrentSet3());
            control.setDeviceId(controlData.getDeviceId());
            control.setOperator(controlData.getOperator());
            control.setPowerFactorSet1(controlData.getPowerFactorSet1());
            control.setSwitchSet1(controlData.getSwitchSet1());
            control.setSwitchSet2(controlData.getSwitchSet2());
            control.setSwitchSet3(controlData.getSwitchSet3());

            boolean count = controlService.save(control);
            if (count == true) {

                //下发控制消息到mqtt-broker
                int lc1 = (int) Math.pow(control.getLeakageCurrentSet1() / 1000.0 * 4096 / 3.3, 2) * 20;
                int lc2 = (int) Math.pow(control.getLeakageCurrentSet2() / 1000.0 * 4096 / 3.3, 2) * 20;
                int lc3 = (int) Math.pow(control.getLeakageCurrentSet3() / 1000.0 * 4096 / 3.3, 2) * 20;
//                Double sdl = control.getSwitchDelaySet1();
                Double sdl = 800.0;
                //格式化下发数据
                String data = String.format("devcrl@%d,%d,%d,%d,%d,%d,%.0f,%.0f,%.0f", control.getSwitchSet1(),
                        control.getSwitchSet2(), control.getSwitchSet3(), lc1, lc2, lc3, control.getPowerFactorSet1() * 100,
                        sdl, control.getCtVarValue());
                System.out.println(controlData);
                //下发数据到mqtt
                mqttSendSevice.sendToMqtt(controlData.getDevice_id(), data);
                return CommonResult.success(count);
            }
            return CommonResult.failed();
        }

    }
}
